package com.bodystm.temperature.controller;

import java.io.BufferedOutputStream;
import java.io.Console;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.bodystm.temperature.bed.Bed;
import com.bodystm.temperature.bed.BedService;
import com.bodystm.temperature.patient.Patient;
import com.bodystm.temperature.patient.PatientBedService;
import com.bodystm.temperature.patient.PatientBedUser;
import com.bodystm.temperature.patient.PatientEquip;
import com.bodystm.temperature.patient.PatientEquipService;
import com.bodystm.temperature.patient.PatientService;
import com.bodystm.temperature.server.ByteUtil;
import com.bodystm.temperature.server.Temperature;
import com.bodystm.temperature.server.TemperatureService;
import com.bodystm.temperature.server.UrineBag;
import com.bodystm.temperature.server.UrineBagService;
import com.bodystm.temperature.web.ConcentratorDevice;
import com.bodystm.temperature.web.DeviceSettings;
import com.bodystm.temperature.web.EasyUiMessage;
import com.bodystm.temperature.web.TemperatureDevice;
import com.bodystm.temperature.web.UrineBagDevice;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.common.system.user.UserService;
import com.mimosa.util.config.Page;

@Controller
@RequestMapping("/patient")
public class PatientController {
	@Resource 
	private UserService userService;
	@Resource 
	private PatientBedService patientBedUserService;
	@Resource
	private PatientService patientService;
	//@Resource
	//private PatientBedService patientBedService;
	@Resource
	private BedService bedService;
	@Resource
	private TemperatureService temperatureService;
	@Resource
	private UrineBagService urineBagService;
	@Resource
	private PatientEquipService patientEquipService;

	@RequestMapping("/index.action")
	public String index() {
		return "patient/patientManage";
	}
	
	@ResponseBody
	@RequestMapping("/getPatientById.action")
	public String getPatientById(String id) {
		try {
			Patient patient=patientService.getEntity(id);
			StringBuilder builder = new StringBuilder();

			Date date = null;
			builder.append("{\"id\":\"").append(patient.getId());
			builder.append("\",\"bedid\":\"").append(patient.getBed()==null?"":patient.getBed().getName());
			builder.append("\",\"idofbed\":\"").append(patient.getBed()==null?"":patient.getBed().getId());
			builder.append("\",\"name\":\"").append(patient.getName());
			builder.append("\",\"sex\":\"").append(patient.getSex());
			builder.append("\",\"sickname\":\"").append(patient.getDisease());
			builder.append("\",\"personid\":\"").append(patient.getPersonnelId());
			builder.append("\",\"sickid\":\"").append(patient.getMedicalRecordNumber());
			if(patient.getListenStartTime()!=null)
			builder.append("\",\"listentime\":\"").append(DateFormatUtils.format(patient.getListenStartTime(),"MM-dd HH:mm")+"~");
			if(patient.getListenEndTime()!=null)
				builder.append("\",\"listentime\":\"").append(DateFormatUtils.format(patient.getListenEndTime(),"MM-dd HH:mm"));
			date = patient.getStartTime();
			builder.append("\",\"roomtime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
			}
			date = patient.getEndTime();
			builder.append("\",\"endTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd"));
			}
			builder.append("\",\"doctor\":\"").append(patient.getDoctor());
			builder.append("\",\"nurse\":\"").append(patient.getNurse());
			builder.append("\",\"age\":\"").append(patient.getAge());
			builder.append("\",\"lowNY\":\"").append(patient.getLowNY());
			builder.append("\",\"highNY\":\"").append(patient.getHighNY());
			if(patient.getSamplingTime()!=null)builder.append("\",\"samplingTime\":\"").append(DateFormatUtils.format(patient.getSamplingTime(),"HH:mm"));
			builder.append("\",\"address\":\"").append(patient.getAddress());
			builder.append("\",\"sicktype\":\"").append(patient.getMedicalTreatmentType());
			UrineBag urineBag=urineBagService.getLatestUrineBag(patient.getEquipNo());
			builder.append("\",\"ny\":\"").append(urineBag==null?"":urineBag.getNY());
			builder.append("\",\"nl\":\"").append(urineBag==null?"":urineBag.getNL());
			builder.append("\",\"cardname\":\"").append(patient.getEquipNo()).append("\"}");
			return builder.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "false";
		}
	}
	/*
	 * ��ȡĳ���������еĲ���
	 * ����userId��ʾ����Id
	 */
	@ResponseBody
	@RequestMapping("/list.action")
	public String list(Page<Patient> page,String userId,String patientName) {
		DecimalFormat decimalFormat=new DecimalFormat(".00");//���췽�����ַ��ʽ�������С����2λ,����0����.
		page.setOrder(Page.DESC);
		page.setOrderBy("startTime");
		Page<Patient> patients = this.patientService.findByPage(page,Restrictions.eq("user.id", userId));
		if(StringUtils.isEmpty(patientName)){
			patients = this.patientService.findByPage(page,Restrictions.eq("user.id", userId));
		}else{
			patients = this.patientService.findByPage(page,Restrictions.eq("user.id", userId),Restrictions.like("name", patientName, MatchMode.ANYWHERE));
		}
		//List<Patient> patients;//=page.getResult();//patientService.getAll();
		//patients=patientBedUserService.getPatientsOfDepartment(userId);
		//List<Patient> patients=patientService.getAll();
		StringBuilder builder = new StringBuilder("{\"total\":\"");
		builder.append(patients.getTotalCount());
		//builder.append(page.getTotalCount());
		builder.append("\",\"rows\":[");
		Date date = null;
		for (Patient patient : patients.getResult()) {
			builder.append("{\"id\":\"").append(patient.getId());
			builder.append("\",\"bedid\":\"").append(patient.getBed()==null?"":patient.getBed().getName());
			builder.append("\",\"name\":\"").append(patient.getName());
			builder.append("\",\"sex\":\"").append(patient.getSex());
			builder.append("\",\"diagnosis\":\"").append(patient.getDisease());
			builder.append("\",\"personnelId\":\"").append(patient.getPersonnelId());
			builder.append("\",\"sickid\":\"").append(patient.getMedicalRecordNumber());
			if(patient.getEndTime()!=null){
				builder.append("\",\"status\":\"").append(0);
			}else{
				builder.append("\",\"status\":\"").append(1);
			}
			if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null){
				builder.append("\",\"listentime\":\"").append(DateFormatUtils.format(patient.getListenStartTime(),"MM-dd HH:mm")+"~"+DateFormatUtils.format(patient.getListenEndTime(),"MM-dd HH:mm"));
			}
				
			
			date = patient.getStartTime();
			builder.append("\",\"startTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
			}
			date = patient.getEndTime();
			builder.append("\",\"endTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
			}
			builder.append("\",\"doctor\":\"").append(patient.getDoctor());
			builder.append("\",\"nurse\":\"").append(patient.getNurse());
			builder.append("\",\"age\":\"").append(patient.getAge());
//			Temperature temprature=temperatureService.getLatestTemprature(patient.getEquipNo());
			UrineBag urineBag=urineBagService.getLatestUrineBag(patient.getEquipNo());
//			builder.append("\",\"degree\":\"").append(temprature==null?"":temprature.getMeasureNumOne());
			//builder.append("\",\"degree\":\"").append(temprature==null?"":decimalFormat.format(temprature.getMeasureNumOne()));
			builder.append("\",\"ny\":\"").append(urineBag==null?"":urineBag.getNY());
			builder.append("\",\"nl\":\"").append(urineBag==null?"":urineBag.getNL());
			builder.append("\",\"cardnum\":\"").append(patient.getEquipNo()).append("\"},");
		}
		if(patients.getTotalCount()>0)
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]}");

		return builder.toString();
	}

//	@ResponseBody
//	@RequestMapping("/list.action")
//	public String list(Page<Patient> page) {
//		page = this.patientService.findByPage(page);
//		StringBuilder builder = new StringBuilder("{\"total\":\"");
//		builder.append(page.getTotalCount());
//		builder.append("\",\"rows\":[");
//		Date date = null;
//		for (Patient patient : page.getResult()) {
//			builder.append("{\"id\":\"").append(patient.getId());
//			builder.append("\",\"name\":\"").append(patient.getName());
//			builder.append("\",\"sex\":\"").append(patient.getSex());
//			date = patient.getStartTime();
//			builder.append("\",\"startTime\":\"");
//			if (date != null) {
//				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd"));
//			}
//			date = patient.getEndTime();
//			builder.append("\",\"endTime\":\"");
//			if (date != null) {
//				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd"));
//			}
//			builder.append("\",\"doctor\":\"").append(patient.getDoctor());
//			builder.append("\",\"nurse\":\"").append(patient.getNurse());
//			builder.append("\",\"age\":\"").append(patient.getAge());
//			builder.append("\",\"equipNo\":\"").append(patient.getEquipNo()).append("\"},");
//		}
//		builder.deleteCharAt(builder.length() - 1);
//		builder.append("]}");
//
//		return builder.toString();
//	}

	/*@ResponseBody
	@RequestMapping("/save.action")
	public String save(Patient patient,String bedName,String userId) {
		Bed bed=bedService.getBedByName(bedName,userId);
		TUser user=userService.getEntity(userId);
		if(bed==null){
			return "{\"success\":false,\"bedstatus\":\""+null+"\"}";
		}else if(!bed.getStatus().equals("empty")){
			
		}else{
			
		}
		
		PatientEquip patientEquip=null;
		try {
			if(patient.getId()!=null&&patient.getId().length()>0){//如果是修改病人信息
				Patient patientTempOld=patientService.getEntity(patient.getId());
				patient.setListenStartTime(patientTempOld.getListenStartTime());
				if(patientTempOld.getBed().getName().equals(bedName)){
					//if(!bed.getStatus().equals("empty")) return "{\"success\":false,\"bedstatus\":\""+bed.getStatus()+"\"}";
				}
				else{
					//判断是否为两个病人换病床
					if(true){//
						
					}else{
						
					}
					Bed bedTempOld=bedService.getBedByName(patientTempOld.getBed().getName(),userId);
					bedTempOld.setStatus("empty");
					PatientBedUser patientBedUserOld=patientBedUserService.getPatientBedUserByPatientAnddBed(patient.getId(), bedTempOld.getId());
					if(patientBedUserOld!=null){
						patientBedUserOld.setStatus(0);
						patientBedUserOld.setStatusOfDepartment(0);
						patientBedUserService.saveEntity(patientBedUserOld);
						
					}
					bedService.saveEntity(bedTempOld);
				}
				//添加设备与病人关系表记录
				if(!patientTempOld.getEquipNo().equals(patient.getEquipNo())){
					patientEquip=new PatientEquip();
					patientEquip.setEquipNo(patient.getEquipNo());
					patientEquip.setPatient(patient);
				}
			}
			else{//如果是新加病人信息
				if(!bed.getStatus().equals("empty")) return "{\"success\":false,\"bedstatus\":\""+bed.getStatus()+"\"}";
				patient.setListenStartTime(new Date());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		bed.setStatus("notempty");
		patient.setBed(bed);
		patient.setUser(user);//
		patient.setListenStartTime(new Date());
		patient.setEquipNo(patient.getEquipNo().toUpperCase());
		
		PatientBedUser patientBedUser=new PatientBedUser();
		patientBedUser.setBed(bed);
		patientBedUser.settUser(user);
		patientBedUser.setPatient(patient);
		patientBedUser.setStatus(1);
		patientBedUser.setStatusOfDepartment(1);
		
		this.patientService.saveEntity(patient);
		patientBedUserService.saveEntity(patientBedUser);
		return "{\"success\":true}";
	}*/
	@ResponseBody
	@RequestMapping("/save.action")
	public String save(Patient patient,String bedName,String userId) {
		Bed bed=bedService.getBedByName(bedName,userId);//获取新的床位
		if(bed==null){
			return "{\"success\":false,\"bedstatus\":\""+null+"\"}";
		}
		TUser user=userService.getEntity(userId);//获取当前用户（科室）
		if(patient.getId()!=null&&patient.getId().length()>0){//如果是修改病人信息
			Patient patientTempOld=patientService.getEntity(patient.getId());//旧病人
			String strOldMac=patientTempOld.getEquipNo();
			patient.setListenStartTime(patientTempOld.getListenStartTime());
			patient.setBed(bed);
			patient.setUser(user);
			patient.setCreateTime(patientTempOld.getCreateTime());
			
			//添加设备与病人关系表记录
			if(!strOldMac.equals(patient.getEquipNo())){//如果换了新的温度贴片,则新加病人与设备对应关系记录
				patient.setEquipNo(patient.getEquipNo().toUpperCase());
				patient.setListenStartTime(new Date());
				PatientEquip patientEquip=new PatientEquip();
				patientEquip.setEquipNo(patient.getEquipNo());
				patientEquip.setPatientID(patient.getId());
				patientEquipService.saveEntity(patientEquip);
			}
			//判断是否修改了床位信息
			if(patientTempOld.getBed().getName().equals(bedName)){//如果床位没有变，只修改了基本信息，则直接存储
				/*patient.setBed(bed);
				patient.setUser(user);*/
				this.patientService.saveEntity(patient);
			}else{//如果修改了床位
				Bed bedTempOld=bedService.getBedByName(patientTempOld.getBed().getName(),userId);
				if(!bed.getStatus().equals("empty")){//判断新的床位是否已经有病人，如果有病人则交换床位
					PatientBedUser pbu2=patientBedUserService.getPatientBedUserByBedName(bedName);//要与其交换的病人关系记录
					/*Patient patientTemp2=(pbu2==null)?null:pbu2.getPatient();//病人2
					if(patientTemp2!=null){
						PatientBedUser patientBedUserOld2=patientBedUserService.getPatientBedUserByPatientAnddBed(patientTemp2.getId(), pbu2.getBed().getId());
						if(patientBedUserOld2!=null){
							patientBedUserOld2.setStatus(0);
							patientBedUserOld2.setStatusOfDepartment(0);
							patientBedUserService.saveEntity(patientBedUserOld2);
						}
					}*/
					pbu2.getPatient().setBed(bedTempOld);
					this.patientService.saveEntity(pbu2.getPatient());
					this.patientService.saveEntity(patient);
					pbu2.setBed(bedTempOld);
					patientBedUserService.saveEntity(pbu2);
				}else{//如果是换空床
					this.patientService.saveEntity(patient);
					bedTempOld.setStatus("empty");
					bed.setStatus("notempty");
					/*PatientBedUser patientBedUserOld=patientBedUserService.getPatientBedUserByPatientAnddBed(patient.getId(), bedTempOld.getId());
					if(patientBedUserOld!=null){
						patientBedUserOld.setStatus(0);
						patientBedUserOld.setStatusOfDepartment(0);
						patientBedUserService.saveEntity(patientBedUserOld);
					}*/
					bedService.saveEntity(bedTempOld);
				}
				PatientBedUser patientBedUserOld=patientBedUserService.getPatientBedUserByPatientAnddBed(patient.getId(), bedTempOld.getId());
				if(patientBedUserOld!=null){
					//patientBedUserOld.setStatus(0);
					//patientBedUserOld.setStatusOfDepartment(0);
					patientBedUserOld.setBed(bed);
					patientBedUserOld.setPatient(patient);//为了保存新的病人的信息					
					patientBedUserService.saveEntity(patientBedUserOld);
				}
//				PatientBedUser patientBedUser=new PatientBedUser();//直接修改不用新建了
//				patientBedUser.setBed(bed);
//				patientBedUser.settUser(user);
//				patientBedUser.setPatient(patient);
//				patientBedUser.setStatus(1);
//				patientBedUser.setStatusOfDepartment(1);
//				patientBedUserService.saveEntity(patientBedUser);
			}
			
			
			/*patient.setBed(bed);
			patient.setUser(user);
			this.patientService.saveEntity(patient);*/
			if(DeviceSettings.lstMacs.contains(patient.getEquipNo())){
				UrineBagDevice urineBagDevice=(UrineBagDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
				if(urineBagDevice!=null&&patient.getSamplingTime()!=null){
					urineBagDevice.setSamplingTime(patient.getSamplingTime());
				}
			}
		}else{//新加病人
			if(!bed.getStatus().equals("empty")) return "{\"success\":false,\"bedstatus\":\""+bed.getStatus()+"\"}";
			patient.setListenStartTime(new Date());
			bed.setStatus("notempty");
			patient.setBed(bed);
			patient.setUser(user);//
			/*patient.setListenStartTime(new Date());*/
			patient.setEquipNo(patient.getEquipNo().toUpperCase());
			
			PatientBedUser patientBedUser=new PatientBedUser();
			patientBedUser.setBed(bed);
			patientBedUser.settUser(user);
			patientBedUser.setPatient(patient);
			patientBedUser.setStatus(1);
			patientBedUser.setStatusOfDepartment(1);
			
			
			this.patientService.saveEntity(patient);
			patientBedUserService.saveEntity(patientBedUser);
			//添加设备与病人关系表记录
			PatientEquip patientEquip=new PatientEquip();
			patientEquip.setPatientID(patient.getId());
			patientEquip.setEquipNo(patient.getEquipNo());
			patientEquipService.saveEntity(patientEquip);
			
		}
		return "{\"success\":true}";
	}
	
	/*
	 * 病人出院
	 */
	@ResponseBody
	@RequestMapping("/patientout.action")
	public String patientout(String id) {
		Patient patient=patientService.getEntity(id);
		if(patient==null)return "{\"success\":false}";
		patient.setEndTime(new Date());
		patient.getBed().setStatus("empty");
		patientService.saveEntity(patient);
		PatientBedUser pbu=patientBedUserService.getPatientBedUserByPatientAnddBed(patient.getId(), patient.getBed().getId());
		pbu.setStatus(0);
		pbu.setStatusOfDepartment(0);
		patientBedUserService.saveEntity(pbu);
		return "{\"success\":true}";
	}
	
	@ResponseBody
	@RequestMapping("/changeBed.action")
	public String changeBed(String patientid,String oldbedid,String newbedid){
		Bed oldbed=this.bedService.getEntity(oldbedid);
		Bed newbed=this.bedService.getEntity(newbedid);
		Patient patient=this.patientService.getEntity(patientid);
		if(patient==null||oldbed==null||newbed==null)return "{\"success\":false}";
		oldbed.setStatus("empty");
		this.bedService.saveEntity(oldbed);
		patient.setBed(newbed);
		patientService.saveEntity(patient);
		PatientBedUser pbu=patientBedUserService.getPatientBedUserByPatientAnddBed(patientid, oldbedid);
		pbu.setStatus(0);
		pbu.setStatusOfDepartment(0);
		patientBedUserService.saveEntity(pbu);
		PatientBedUser newPBU=new PatientBedUser();
		newbed.setStatus("notempty");
		newPBU.setBed(newbed);
		newPBU.setPatient(patient);
		newPBU.settUser(newbed.getUser());
		newPBU.setStatus(1);
		newPBU.setStatusOfDepartment(1);
		patientBedUserService.saveEntity(newPBU);
		return "{\"success\":true}";
	}

	@ResponseBody
	@RequestMapping("/update.action")
	public String update(Patient patient) {
		this.patientService.saveEntity(patient);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Patient patient,String bedname,HttpSession session) {
		Bed bed=bedService.getBedByName(bedname,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		if(bed!=null){
		bed.setStatus("empty");
		bedService.saveEntity(bed);
		}
//		this.patientBedUserService.deleteByPatientId(patient.getId());
		//java.util.List<PatientBedUser> lstPBU=this.patientBedUserService.findList("from PatientBedUser t where t.patient.id=?", patient.getId());
		try {
			this.patientBedUserService.deleteByPatientId(patient.getId());
//			for(PatientBedUser item:patient.getBedList()){
//				this.patientBedUserService.deleteEntity(item);
////				this.patientBedUserService.deleteByPatientId(patientId);(item);
//			}
			this.patientService.deleteEntity(patient);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new EasyUiMessage().toString();
	}
	
	/**
	 * 根据身份证号删除病人
	 * @param personnelId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteById.action")
	public String deleteById(String personnelId) {
		
		this.patientService.deleteById(personnelId);
		return Boolean.TRUE.toString().toLowerCase();
	}
	
	@ResponseBody
	@RequestMapping("/correctDegree.action")
	public String correctDegree(String strMac,float correctNum) {
		Patient patient=this.patientService.getPatientByMac(strMac);
		if(patient!=null){
			patient.setNum4Correct(correctNum);
			patientService.saveEntity(patient);
			if(DeviceSettings.lstMacs.contains(strMac)){
				TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strMac);
				temperatureDevice.setNum4Correct(correctNum);
			}else{
				DeviceSettings.lstMacs.add(strMac);
				TemperatureDevice temperatureDevice=new TemperatureDevice();
				temperatureDevice.setNum4Correct(correctNum);
				temperatureDevice.setStrMac(strMac);
				DeviceSettings.hasDevice.put(strMac, temperatureDevice);
			}
			return Boolean.TRUE.toString().toLowerCase();
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/sendCMD.action")
	public String sendCMD(String mac,String cmd) throws IOException {
		try {
			UrineBagDevice urineBagDevice=null;
			if(DeviceSettings.lstMacs.contains(mac)){
				urineBagDevice = (UrineBagDevice)DeviceSettings.hasDevice.get(mac);
			}
			if (urineBagDevice!=null) {
				Socket socket=urineBagDevice.getSocket();
				if (socket==null||!socket.isConnected()) {
					return Boolean.FALSE.toString().toLowerCase();
				}
				//byte b=new Byte(cmd);//(byte) Integer.parseInt("7E", 16);
				byte[] msgs=new byte[8];
				msgs[0]=0x7e;
				msgs[7]=(byte) Integer.parseInt(cmd, 16);
				for(int i=1;i<=6;i++){
					msgs[i]=(byte) Integer.parseInt(mac.substring(2*i-2,2*i), 16);
				}
				
				BufferedOutputStream pw = null;
				OutputStream socketOut = socket.getOutputStream();
				pw= new BufferedOutputStream(socketOut);
				pw.write(msgs);
				pw.flush();
				System.out.println(msgs[7]);
				return Boolean.TRUE.toString().toLowerCase();
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Boolean.FALSE.toString().toLowerCase();
		}
		
		return Boolean.FALSE.toString().toLowerCase();
	}
}